package com.youlai.system.controller;

import com.youlai.system.common.result.Result;
import com.youlai.system.common.util.CommUtils;
import com.youlai.system.global.GlobalData;
import com.youlai.system.model.entity.TimeProgram;
import com.youlai.system.model.vo.TimeProgramScrollListVO;
import com.youlai.system.plugin.dupsubmit.annotation.PreventDuplicateSubmit;
import com.youlai.system.service.TimeProgramService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "900.时间程序")
@RestController
@RequestMapping("/api/v1/timeprogram")
@RequiredArgsConstructor
public class TimeProgramController {

    private final TimeProgramService timeProgramService;

    @GetMapping
    @Operation(summary = "获取所有时间程序")
    public Result<List<TimeProgram>> getAllTimeProgram(){
        List<TimeProgram> timeProgramList = timeProgramService.list();
        return Result.success(timeProgramList);
    }
    @PutMapping
    @Operation(summary = "更新信息")
    @PreAuthorize("@ss.hasPerm('sys:timeProgram:edit')")
    public Result<Boolean> updateTimeProgram( @RequestBody TimeProgram timeProgram) {
        if(GlobalData.opcUaHelper.isConnected){
            timeProgram.setTime(CommUtils.getCurrentDateTime());
            return Result.judge(timeProgramService.saveAndDownloadById(timeProgram));
        }else{
            return Result.failed("请连接PLC!");
        }
    }

    @Operation(summary = "获取scroll数据")
    @PostMapping("/scroll")
    public Result<List<TimeProgramScrollListVO>> getTimeProgramScroll(
            @RequestBody String desc) {
        return Result.success(timeProgramService.getTimeProgramScroll(desc));
    }

    @GetMapping("/{id}")
    @Operation(summary = "通过Id获取信息")
    public Result<TimeProgram> getTimeProgramById(@PathVariable Long id){
        return Result.success(timeProgramService.getById(id));
    }

    @PostMapping("/save")
    @PreventDuplicateSubmit
    @Operation(summary = "添加")
    @PreAuthorize("@ss.hasPerm('sys:timeProgram:add')")
    public Result<Boolean> saveTimeProgram( @Valid @RequestBody TimeProgram timeProgram){
        return Result.success(timeProgramService.saveTimeProgram(timeProgram));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除信息")
    @PreAuthorize("@ss.hasPerm('sys:timeProgram:delete')")
    public Result<Boolean> deleteTrend(@PathVariable String id)  {
        return Result.success(timeProgramService.removeById(id));
    }

}